
const nums = [1, 2, 3, 4, 5, 6, 7], k = 3
// 输出: [5,6,7,1,2,3,4]
// 向右轮转 1 步: [7,1,2,3,4,5,6]
// 向右轮转 2 步: [6,7,1,2,3,4,5]
// 向右轮转 3 步: [5,6,7,1,2,3,4]

// 插入法
var rotate1 = function (nums, k) {
  for (let i = 0; i < k; i++) {
    const last = nums.pop();
    nums.unshift(last);
  }
  return nums
};


// 数组翻转法
var rotate = function (nums, k) {
  k = k % nums.length;// k大于数组本身
  // 翻转全部
  reverse(nums, 0, nums.length - 1);
  // 从k中间切割 翻转左边
  reverse(nums, 0, k - 1);
  // 翻转右边
  reverse(nums, k, nums.length - 1);
  return nums;
};

function reverse(nums, start, end) {
  while (start < end) {
    const temp = nums[start];
    nums[start] = nums[end];
    nums[end] = temp;
    start++;
    end--;
  }
}


console.log(rotate(nums, k));
